<template>
  <div class="app-container">
      <!-- 搜索和添加 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="">
        <el-input v-model="userMap.data.userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-select v-model="userMap.data.userType" clearable filterable placeholder="人员类型">
            <!-- 人员类型(1:客服账号;2:管理账号;3:内置账号;4：财务账号 5：物流账号) -->
            <el-option  label="客服账号" value="1"></el-option>
            <el-option  label="管理账号" value="2"></el-option>
            <el-option  label="内置账号" value="3"></el-option>
            <el-option  label="财务账号" value="4"></el-option>
            <el-option  label="物流账号" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" @click="batchUser">批量删除</el-button>
      </el-form-item>
    </el-form>

  <!-- 修改用户信息表单 -->
  <el-dialog title="用户修改" :visible.sync="dialogFormVisible" :rules="rules" width="30%" center @close="closeWindow()">
    <el-form :model="editForm" size="mini">
      <el-form-item label="用户ID" v-if="false">
        <el-input v-model="editForm.userId" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item label="用户名称">
        <el-input v-model="editForm.userName" style="width:300px" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="人员类型">
        <el-select v-model="editForm.userType" clearable filterable placeholder="人员类型">
            <!-- 人员类型(1:客服账号;2:管理账号;3:内置账号;4：财务账号 5：物流账号) -->
            <el-option  label="客服账号" value="1"></el-option>
            <el-option  label="管理账号" value="2"></el-option>
            <el-option  label="内置账号" value="3"></el-option>
            <el-option  label="财务账号" value="4"></el-option>
            <el-option  label="物流账号" value="5"></el-option>
        </el-select>
      </el-form-item>
      <!-- class="el-checkbox-button el-checkbox-button--mini"
      el-checkbox-button el-checkbox-button--mini is-checked -->
      <el-form-item label="用户角色">
        <template>
          <el-checkbox-group v-model="roleNames">
            <el-checkbox-button v-for="(item,index) in userRolesList" :key="index" :label="item.roleName" :value="item.roleName" ></el-checkbox-button>
          </el-checkbox-group>
        </template>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveUpdate()">确 定</el-button>
    </div>
  </el-dialog>

<!-- 表单显示用户列表 -->
    <el-table ref="multipleTable" :data="userList" height="350" border style="width: 100%">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="userId" label="用户Id" width="180" v-if="false"> </el-table-column>
        <el-table-column prop="userName" label="用户名" width="180"> </el-table-column>
        <el-table-column prop="account" label="账户" width="180"> </el-table-column>
        <el-table-column prop="userType" label="人员类型" :formatter="userTypeList" width="180"></el-table-column>
        <el-table-column prop="roles" label="用户角色" :formatter="rolesList" ></el-table-column>
        <el-table-column prop="enabled" label="账号状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-value="1"
            active-color="#00A854"
            inactive-value="0"
            inactive-color="#F04134"
            @change="changeEnabled(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
                  <div>
                      <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRow(scope.row)"></el-button>
                      <el-button size="mini" type="warning" icon="el-icon-delete" @click="deleteRow(scope.row)"></el-button>
                  </div>
              </template>
        </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10, 15, 30]"
        :page-size="userMap.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
  
</template>
<script>
//引用role相关的api
import { userSearch, saveUpdateUser ,userRole,deleteUser,batchDeleteUser,changeEnabled} from "@/api/userList.js";

export default {
  data() {
    return {
        dialogFormVisible:false,
        pages:0,
        total:0,
        roleNames:[],
        currentRowRoleIds:[],
        userList:[],
        editForm:{},
        roleLists:[],
        userIdRoleCode:[],
        userRolesList:[],
        userRole:[],
        userMap:{
            page:1,
            limit:5,
            data:{
            }
        },
        rules:{
          userName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
          userType: [{ required: true, message: "请选择用户类型", trigger: "blur" }],
        }
    };
  },

  methods: {
      // 弹出层
      dialogFormView(){
        this.dialogFormVisible = true;
      },
      //分页：选择每页显示多少页
      handleSizeChange(val) {
        this.userMap.limit = `${val}`;
        this.search();
      },
      //分页：选择第几页
      handleCurrentChange(val) {
          this.userMap.page = `${val}`;
          this.search();
      },
      //搜索功能
      search(){//搜索
       var _this = this;
        userSearch(this.userMap).then(res => {
            _this.userList = res.data; //当前页数据
            _this.total = res.total; //总记录数
            _this.pages = res.pages; //总页数
            console.log(res);
            console.log(_this.userList);
        });
        this.$forceUpdate();
        console.log(_this.userList);
      },
      //获取所有的角色列表
      userRoleList(){
          var _this = this;
          userRole().then(res=>{
              _this.userRolesList = res.data;
          });
      },
      // 编辑当前行
      editRow(rowData){
        this.userRoleList();
          var _this = this ;
          this.editForm=rowData;
          _this.roleNames=[];
          rowData.roles.forEach(e=>{
            var obj = e.roleName;
            var objArr = obj.split(",");
            objArr.forEach(item=>{
              _this.roleNames.push(item)
            })
          })
          this.dialogFormVisible = true;
      },
      //删除当前行
      deleteRow(rowData){
        console.log(rowData);
        this.$confirm('即将删除该用户, 是否继续?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          deleteUser(rowData).then(res=>{
              this.$message({
              type: res.success?'success':'false',
              message: res.message
            });
          })
          this.search();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 保存修改内容
      saveUpdate(){
        var _this = this;
        _this.$refs[basicsform].validate((valid) =>{
          if(valid){
            _this.userIdRoleCode=[];
            this.editForm.userRole=[];
            this.userRolesList.forEach(e=>{
              _this.roleNames.forEach(r=>{
                if(r == e.roleName){
                    _this.userIdRoleCode.push({"userId":_this.editForm.userId,"roleId":e.roleCode});
                }
              })
            })
            this.editForm.userRole=this.userIdRoleCode;
            saveUpdateUser(this.editForm).then(res=>{
              // vm.$set(vm.items, indexOfItem, newValue)
              this.$message({
                type: res.success?'success':'false',
                message: res.message
              });
              this.search();
            })
            this.dialogFormVisible = false;
          }else{
            this.$message({
              message: "请按照要求输入",
              type: "warning",
            });
            return false;
          }
        })
        
      },
    // 批量删除用户
    batchUser() {
      let selectData = [];
      selectData = this.$refs.multipleTable.selection;
      if(selectData.length == 0){
          this.$message({
            message: '您还未选中删除对象',
            type: 'info'
          });
      }else{
        // 删除消息提示
        this.$confirm("此操作将永久删除用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let ids = [];
          selectData.forEach((item) => {
            ids.push(item.userId);
          });
          // console.log(ids);
          batchDeleteUser(ids).then((res) => {
            this.$message({
              message: res.message,
              type: res.success ? "success" : "warning",
            });
            this.search();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    changeEnabled(rowData){
      console.log(rowData);
      changeEnabled(rowData).then(res=>{
        this.$message({
            message: res.message,
            type: res.success ? "success" : "warning",
          });
          this.search();
      })
    },
    
    //用户账号类型
    userTypeList (row) {
        var str = "";
        // 1:客服账号;2:管理账号;3:内置账号;4：财务账号 5：物流账号
        if(row.userType == 1){
            str = "客服账号";
        }else if(row.userType == 2){
            str = "管理账号";
        }else if(row.userType == 3){
            str = "内置账号";
        }else if(row.userType == 4){
            str = "财务账号";
        }else if(row.userType == 5){
            str = "物流账号";
        }
        return str;
    },
    //用户所拥有的角色名称
    rolesList(row){
        var str = "";
        var roleList = row.roles;
        var roleTemp = [];
        roleList.forEach(rs=>{
            
            roleTemp.push(rs.roleName);
            str = roleTemp.join("、");
        })
        return str;
    },
    closeWindow(){
      this.search();
    },
    //表单校验
    rule:{
      userName:[
        {required: true, message: '请输入用户名', trigger: 'blur'}
      ]
    }
  },
  mounted() {
    //页面加载
    this.search();
    // this.userRoleList();
  },

};
</script>